package com.nowcoder.controller;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.entity.Message;
import com.nowcoder.entity.Page;
import com.nowcoder.entity.User;
import com.nowcoder.service.MessageService;
import com.nowcoder.service.UserService;
import com.nowcoder.utils.CommunityConstant;
import com.nowcoder.utils.CommunityUtil;
import com.nowcoder.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller
@RequestMapping("/letter")
public class MessageController implements CommunityConstant {
    @Autowired
    MessageService messageService;

    @Autowired
    UserService userService;

    @GetMapping("/list")
    public String getLetterList(Model model, Page page) {
        User user = HostHolder.getUser();

        // ?????????
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.findConversationCount(user.getId()));

        // ???б?
        List<Message> conversationsList = messageService.findConversations(user.getId(),
                page.getOffset(), page.getLimit());
        // ???????б?
        List<Map<String, Object>> conversations = new ArrayList<>();
        for(Message message: conversationsList) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("conversation", message);
            map.put("letterCount", messageService.findLetterCount(message.getConversationId()));
            map.put("unreadCount", messageService.findLetterUnreadCount(user.getId(), message.getConversationId()));
            int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
            map.put("target", userService.findUserById(targetId));
            conversations.add(map);
        }
        model.addAttribute("conversations", conversations);

        // ??????δ??????
        int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);

        int noticeUnreadCount = messageService.findNoticeUnreadCount(HostHolder.getUser().getId(), null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);

        return "/site/letter";
    }
    @GetMapping("/detail/{conversationId}")
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page page, Model model) {
        System.out.println("1111");
        // ??????
        page.setLimit(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setRows(messageService.findLetterCount(conversationId));

        // ????б?
        List<Message> letterList = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());
        List<Map<String, Object>> letters = new ArrayList<>();
        for (Message message : letterList) {
            Map<String, Object> map = new HashMap<>();
            map.put("letter", message);
            map.put("fromUser", userService.findUserById(message.getFromId()));
            letters.add(map);
        }
        model.addAttribute("letters", letters);

        // ??????
        model.addAttribute("target", getLetterTarget(conversationId));
        List<Integer> letterIds = getLetterIds(letterList);
        if(!letterIds.isEmpty()) {
            messageService.readMessage(letterIds);
        }

        return "/site/letter-detail";
    }

    private List<Integer> getLetterIds(List<Message> letterList) {
        List<Integer> ids =  new ArrayList<>();
        for(Message message: letterList) {
            if(HostHolder.getUser().getId() == message.getToId() &&
                message.getStatus() == 0) {
                ids.add(message.getId());
            }
        }
        return ids;
    }

    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if (HostHolder.getUser().getId() == id0) {
            return userService.findUserById(id1);
        } else {
            return userService.findUserById(id0);
        }
    }

    @PostMapping("/send")
    @ResponseBody
    public String sendLetter(String toName, String content) {
        toName = toName.trim();
        User target = userService.findUserByName(toName);
        if(target == null) {
            return CommunityUtil.getJSONString(1, "????????????");
        }
        Message message = new Message();
        message.setFromId(HostHolder.getUser().getId());
        message.setToId(target.getId());
        if(message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        }else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }
        message.setContent(content);
        message.setCreateTime(new Date());
        System.out.println(message);
        messageService.addMessage(message);

        return CommunityUtil.getJSONString(0);
    }

    @GetMapping("/notice/list")
    public String getNoticeList(Model model) {
        System.out.println("getNoticeList----->");
        System.out.println("getNoticeList----->");
        System.out.println("getNoticeList----->");
        System.out.println("getNoticeList----->");
        System.out.println("getNoticeList----->");
        Map<String, Object> commentNotice = getOneNoticeList(TOPIC_COMMENT);
        model.addAttribute("commentNotice", commentNotice);

        Map<String, Object> likeNotice = getOneNoticeList(TOPIC_LIKE);
        model.addAttribute("likeNotice", likeNotice);
        System.out.println(likeNotice);

        Map<String, Object> followNotice = getOneNoticeList(TOPIC_FOLLOW);
        model.addAttribute("followNotice", followNotice);

        int letterUnreadCount = messageService.findLetterUnreadCount(HostHolder.getUser().getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);

        int noticeUnreadCount = messageService.findNoticeUnreadCount(HostHolder.getUser().getId(), null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);
        return "/site/notice";
    }


    private Map<String, Object> getOneNoticeList(String topic) {
        User user = HostHolder.getUser();
        Message message = messageService.findLatestNotice(user.getId(), topic);
        if(message != null) {
            HashMap<String, Object> messageVo = new HashMap<>();
            messageVo.put("message", message);
            String content = HtmlUtils.htmlUnescape(message.getContent());
            HashMap data = JSONObject.parseObject(content, HashMap.class);
            messageVo.put("user", userService.findUserById((Integer) data.get("userId")));
            messageVo.put("entityType", data.get("entityType"));
            messageVo.put("entityId", data.get("entityId"));
            messageVo.put("postId", data.get("postId"));

            int noticeCount = messageService.findNoticeCount(user.getId(), topic);
            messageVo.put("count", noticeCount);

            int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), topic);
            messageVo.put("unread", noticeUnreadCount);
            return messageVo;
        }
        return null;
    }

    @GetMapping("/notice/detail/{topic}")
    public String getNoticeDetail(@PathVariable("topic") String topic, Page page, Model model) {
        User user = HostHolder.getUser();

        page.setLimit(5);
        page.setPath("/notice/detail/" + topic);
        page.setRows(messageService.findNoticeCount(user.getId(), topic));
        List<Message> notices = messageService.findNotices(user.getId(), topic, page.getOffset(), page.getLimit());
        List<Map<String, Object>> noticeVoList = new ArrayList<>();
        for(Message notice: notices) {
            Map<String, Object> map = new HashMap<>();
            // 通知
            map.put("notice", notice);
            // 内容
            String content = HtmlUtils.htmlUnescape(notice.getContent());
            Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
            map.put("user", userService.findUserById((Integer) data.get("userId")));
            map.put("entityType", data.get("entityType"));
            map.put("entityId", data.get("entityId"));
            map.put("postId", data.get("postId"));
            // 通知作者
            map.put("fromUser", userService.findUserById(notice.getFromId()));

            noticeVoList.add(map);
        }
        model.addAttribute("notices", noticeVoList);

        // 设置已读
        List<Integer> ids = getLetterIds(notices);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }
        return "/site/notice-detail";
    }
}




















